from .conn_mysql import ConnectMysql

import re

import datetime

import random

class ApiMysql(ConnectMysql):

    def verify_password(self, pass_word):
    
        if not 6<=len(pass_word)<=20:
    
            return False

        if str(pass_word).isdigit():

            return True

        RE_CHINESE = re.compile(r'^[\u4e00-\u9fa5]{1,8}$')

        if RE_CHINESE.findall(str(pass_word)):
            
            return False

        if str(pass_word).isspace():
    
            return False

        if str(pass_word).isnumeric():
        
            return True

        if str(pass_word).isalnum():
    
            return True

        elif str(pass_word).isalpha():

            return True

        else:

            return False

    def update_password(self, phone, new_pass_word):
        '''传入账户，新密码 ：更改该账户密码'''

        update_sql = '''UPDATE account SET pass_word=%s WHERE phone=%s'''

        result_info = self.update_info(update_sql, (new_pass_word, phone))

        return result_info

    def verify_code(self, phone, verify_code):
        '''验证码是否合法'''

        sql = 'SELECT * FROM phone_verify WHERE verify_code=%s and phone=%s'

        result = self.select_one(sql, (verify_code, phone))

        if not result:

            return False

        time_delta = datetime.timedelta(minutes=5)#有效时间量

        regedate = result['regedate']#datetime类型

        if (regedate + time_delta) < datetime.datetime.now():#时间失效
            
            return False

        else:

            return True

    def verify_phone(self, phone):
        '''验证账号是否已存在，phone'''

        verify_phone_sql = 'select * from account where phone = %s'

        result_info = self.select_all(verify_phone_sql, (phone,))

        if result_info:

            return True

        else:
            return False

    def login(self, phone, pass_word):
        '''login in use your user, password'''

        login_sql = 'select * from account where phone = %s and pass_word = %s'

        result_info = self.select_one(login_sql,(phone, pass_word))

        return result_info

    def register_user(self, phone, pass_word):
        '''new user register user-password'''

        register_sql = 'insert into account(phone, pass_word) values (%s, %s)'

        result_info = self.insert_info(register_sql,(phone, pass_word))

        return result_info

    def login_user(self, methods, phone, pass_word):
        '''login in use your user, password flask_api'''

        if not methods == 'POST':

            return {
                        'status': -1,
                        'errorCode': 1,
                        'errorMsg':f'请检查request.method:{methods}请重新请求',
                        'resultBody':None
                    }

        elif all((phone,pass_word)):

            if not self.is_phone(phone):
    
                return {
                            'status': -1,
                            'errorCode': 4,
                            'errorMsg':f'请检查参数是否合格,phone:{phone}请重新输入',
                            'resultBody':None
                        }

            login_case = self.login(phone, pass_word)

            if login_case:

                return {
                            'status': 1,
                            'errorCode': None,
                            'errorMsg':None,
                            'resultBody':'登录成功'
                        }

            else:

                return {
                            'status': -1,
                            'errorCode': 2,
                            'errorMsg':f'请检查是否注册phone:{phone},pass_word:{pass_word}请重新请求',
                            'resultBody':None
                        }
        
        else:

           return {
                        'status': -1,
                        'errorCode': 3,
                        'errorMsg':f'请检查是否为空phone:{phone},pass_word:{pass_word}请重新请求',
                        'resultBody':None
                    } 

    def is_phone(self, phone):
        '''验证phone格式'''
        phone_pat = re.compile('^(13\d|14[5|7]|15\d|166|17[3|6|7]|18\d)\d{8}$')
        res = re.search(phone_pat, phone)
        if not res:
            return False
        return True

    def register(self, methods, phone, verify_code, pass_word_one, pass_word_two):
        '''new user register user-password flask_api'''
        if not methods == 'POST':

            return {
                        'status': -1,
                        'errorCode': 1,
                        'errorMsg':f'请检查request.method:{methods}请重新请求',
                        'resultBody':None
                    }

        elif all((phone, verify_code, pass_word_one, pass_word_two)):

            if pass_word_one != pass_word_two:

                return {
                            'status': -1,
                            'errorCode': 2,
                            'errorMsg':f'两遍密码不一致，pass_word_one:{pass_word_one},pass_word_two:{pass_word_two}请重新输入',
                            'resultBody':None
                        }

            if not self.verify_password(pass_word_one):

                return {
                            'status': -1,
                            'errorCode': 4,
                            'errorMsg':f'密码格式为数字英文长度6~20，pass_word_one:{pass_word_one},pass_word_two:{pass_word_two}请重新输入',
                            'resultBody':None
                        }

            if not self.is_phone(phone):

                return {
                            'status': -1,
                            'errorCode': 5,
                            'errorMsg':f'请检查参数是否合格,phone:{phone}请重新输入',
                            'resultBody':None
                        }
            
            elif self.verify_phone(phone):

                return {
                            'status': -1,
                            'errorCode': 6,
                            'errorMsg':f',该phone:{phone},已注册请跳转login页面',
                            'resultBody':None
                        }

            elif not self.verify_code(phone, verify_code):

                return {
                            'status': -1,
                            'errorCode': 7,
                            'errorMsg':f',请检查该verify_code:{verify_code},是否已过期或是否正确，请重新请求或确认后重新输入',
                            'resultBody':None
                        }
            
            else:

                if self.register_user(phone, pass_word=pass_word_one):

                    return {
                                'status': 1,
                                'errorCode': None,
                                'errorMsg':None,
                                'resultBody':'注册成功'
                            } 
                
                else:

                    return {
                                'status': -1,
                                'errorCode': 8,
                                'errorMsg':'unknownerror,请联系管理员',
                                'resultBody':None
                            } 

        else:
    
           return {
                        'status': -1,
                        'errorCode': 9,
                        'errorMsg':'请检查参数是否为空请重新请求',
                        'resultBody':None
                    } 

    def reset_password(self, methods, phone, verify_code, new_pass_word_1, new_pass_word_2):
        '''new user register user-password flask_api'''
        if not methods == 'POST':

            return {
                        'status': -1,
                        'errorCode': 1,
                        'errorMsg':f'请检查request.method:{methods}请重新请求',
                        'resultBody':None
                    }

        elif all((phone, verify_code, new_pass_word_1, new_pass_word_2)):

            if new_pass_word_1 != new_pass_word_2:

                return {
                            'status': -1,
                            'errorCode': 2,
                            'errorMsg':f'两遍新密码不一致，new_pass_word_1:{new_pass_word_1},new_pass_word_2:{new_pass_word_2}请重新输入',
                            'resultBody':None
                        }

            if not self.verify_password(new_pass_word_1):
    
                return {
                            'status': -1,
                            'errorCode': 4,
                            'errorMsg':f'密码格式为数字英文长度6~20，new_pass_word_1:{new_pass_word_1},new_pass_word_2:{new_pass_word_2}请重新输入',
                            'resultBody':None
                        }
            
            if not self.is_phone(phone):

                return {
                            'status': -1,
                            'errorCode': 5,
                            'errorMsg':f'请检查参数是否合格,phone:{phone}请重新输入',
                            'resultBody':None
                        }
            
            elif not self.verify_phone(phone):
    
                return {
                            'status': -1,
                            'errorCode': 6,
                            'errorMsg':f'此账户phone:{phone}不存在',
                            'resultBody':None
                        } 
            
            elif not self.verify_code(phone, verify_code):

                return {
                            'status': -1,
                            'errorCode': 7,
                            'errorMsg':f'请检查该verify_code:{verify_code},是否已过期或是否正确，请重新请求或确认后重新输入',
                            'resultBody':None
                        }
        
            else:

                if self.update_password(phone, new_pass_word_1):

                    return {
                                'status': 1,
                                'errorCode': None,
                                'errorMsg':None,
                                'resultBody':'更改成功，请跳转login页面登录'
                            } 

                else:
    
                    return {
                                'status': -1,
                                'errorCode': 8,
                                'errorMsg':'unknownerror,请联系管理员',
                                'resultBody':None
                            } 

        else:
    
           return {
                        'status': -1,
                        'errorCode': 9,
                        'errorMsg':'请检查参数是否为空请重新请求',
                        'resultBody':None
                    } 

    def verify_time_send(self, phone):
        '''select from phone_verify time
        is or not is time out'''
        select_sql = 'select * from phone_verify where phone = %s ORDER BY regedate DESC'

        result_info = self.select_one(select_sql,(phone,))

        if result_info:

            time_delta = datetime.timedelta(minutes=5)#有效时间量

            regedate = result_info['regedate']#datetime类型

            if (regedate + time_delta) > datetime.datetime.now():#时间失效
                
                return False

        return True

    def phone_verify_code(self, phone, verify_code):
        '''insert into phone_verify_code'''

        phone_verify_sql = 'insert into phone_verify(phone, verify_code) values (%s, %s)'

        result_info = self.insert_info(phone_verify_sql,(phone, verify_code))

        return result_info

    def send_verify_code(self, methods, phone):
        '''send in user phone get verify_code'''
        if not methods == 'POST':

            return {
                        'status': -1,
                        'errorCode': 1,
                        'errorMsg':f'请检查request.method:{methods}请重新请求',
                        'resultBody':None
                    }

        verify_code = random.randint(100000,999999)

        if all(phone):

            if not self.is_phone(phone):

                return {
                            'status': -1,
                            'errorCode': 2,
                            'errorMsg':f'请检查参数是否合格,phone:{phone}请重新输入',
                            'resultBody':None
                        }

            elif not self.verify_time_send(phone):

                return {
                            'status': -1,
                            'errorCode': 3,
                            'errorMsg':f'此,phone:{phone}已发送过请在5分钟内使用验证码',
                            'resultBody':None
                        }

            else:

                send_work = self.send_phone_code(phone,verify_code)

                if not send_work:

                    return {
                                'status': -1,
                                'errorCode': 4,
                                'errorMsg':'发送失败，请联系管理员',
                                'resultBody':None
                            }
                else:

                    insert_verify_code = self.phone_verify_code(phone,verify_code)

                    return {
                                'status': 1,
                                'errorCode': None,
                                'errorMsg':None,
                                'resultBody':'发送成功'
                            }

        else:

            return {
                        'status': -1,
                        'errorCode': 6,
                        'errorMsg':f'phone:{phone}为空',
                        'resultBody':None
                    }
                
    def send_phone_code(self, phone, verify_code):
        '''待开发'''

        return 'ok'
